
package com.hmsg.health.controller;


import com.hmsg.health.bean.vo.*;
import com.hmsg.health.dao.AppealDao;
import com.hmsg.health.dao.InviteDao;
import com.hmsg.health.dao.MessageDao;
import com.hmsg.health.dao.ShareDao;
import com.hmsg.health.dao.SigninDao;
import com.hmsg.health.dao.TaskDao;
import com.hmsg.health.dao.TaskTypeDao;
import com.hmsg.health.dao.UserAccountRecordDao;
import com.hmsg.health.dao.UserDao;
import com.hmsg.health.dao.WithdrawDao;
import com.hmsg.health.service.MenWangSMSService;
import com.hmsg.health.service.TaskService;
import com.hmsg.health.service.UserService;
import com.hmsg.health.service.aes.SecurityData;

import org.apache.commons.collections.CollectionUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.Base64Utils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSBuilder;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyuncs.ecs.model.v20140526.DescribeTasksResponse.Task;
import com.aliyuncs.http.HttpResponse;
import com.hmsg.health.bean.Dto.UmengExtra;
import com.hmsg.health.bean.domain.AppealDo;
import com.hmsg.health.bean.domain.InviteDo;
import com.hmsg.health.bean.domain.MessageDo;
import com.hmsg.health.bean.domain.ShareDo;
import com.hmsg.health.bean.domain.SigninDo;
import com.hmsg.health.bean.domain.TaskDo;
import com.hmsg.health.bean.domain.TaskTypeDo;
import com.hmsg.health.bean.domain.UserAccountDo;
import com.hmsg.health.bean.domain.UserAccountRecordDo;
import com.hmsg.health.bean.domain.UserDo;
import com.hmsg.health.bean.domain.UserTaskDo;
import com.hmsg.health.bean.domain.WithdrawDo;
import com.hmsg.health.bean.enums.StatusCode;
import com.hmsg.health.config.Constants;
import com.hmsg.health.config.PropertyConfig;
import com.hmsg.health.param.AccessToken;
import com.hmsg.health.param.ResponseResult;
import com.hmsg.health.security.IgnoreSecurity;
import com.hmsg.health.security.OpenApi;
import com.hmsg.health.security.TokenManager;
import com.hmsg.health.utils.ApiException;
import com.hmsg.health.utils.ErrorCode;
import com.hmsg.health.utils.GetScene;
import com.hmsg.health.utils.HttpResult;
import com.hmsg.health.utils.HttpUtil;
import com.hmsg.health.utils.RandomUtil;
import com.hmsg.health.utils.umeng.push.Demo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Base64.Decoder;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletResponse;

/**
 * @Author Tareva on 2018/11/11.
 * @Description TODO
 */
@Api(value = "用户相关", tags = { "用户相关" })
@Slf4j
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
	StringRedisTemplate stringTemplate;
    @Autowired
  	private MenWangSMSService smsService;
	@Autowired
	private TokenManager tokenManager;
    static final String XCODE_KEY = "XCODE_KEY_";
    @Autowired
  	PropertyConfig propertyConfig;
    @Autowired
    private UserService userService;
    @Autowired
    private SigninDao signinDao;
    @Autowired
    private InviteDao inviteDao;
    @Autowired
    private ShareDao shareDao;
    @Autowired
    private UserAccountRecordDao userAccountRecordDao;
    @Autowired
    private TaskTypeDao taskTypeDao;
    @Autowired
    private TaskDao taskDao;
    @Autowired
    private AppealDao appealDao;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private TaskService taskService;
    @Autowired
    private WithdrawDao withdrawDao;
    @PostMapping("/orderTaking")
    @ApiOperation(value="我的接单", notes="我的接单" ,httpMethod="POST")
    @ResponseBody
    @IgnoreSecurity
	@OpenApi
	@ApiImplicitParams({
		@ApiImplicitParam(name="status", value="0已领取待提交 1已提交待审核 2审核未通过 3 已完成", dataType = "int", required=false, paramType="form"),
		@ApiImplicitParam(name="pageNo", value="页码", dataType = "int", required=false, paramType="form"),
		@ApiImplicitParam(name="pageSize", value="页容", dataType = "int", required=false, paramType="form")
	})
    @SecurityData
	public  ResponseResult<List<UserTaskDo>> tasks(@RequestHeader(Constants.CLIENT_USER) Integer userId,@RequestBody @Validated UserTaskVo vo) {
    	UserTaskDo task = new UserTaskDo();
    	
    	if(vo.getPageNo()!=null){
			Integer startNo = (vo.getPageNo()-1)*vo.getPageSize();
			task.setStartNo(startNo);
			task.setPageSize(vo.getPageSize());
		}
    	if(vo.getStatus()!=null){
			task.setStatus(vo.getStatus());
		}
    	task.setUserId(userId);
    	List<UserTaskDo> tasks = userService.orderTaking(task);
    	if(tasks!=null&&tasks.size()>0){
    		for(UserTaskDo ut:tasks){
    			if(ut.getTask().getTypeDo()!=null){
    				TaskTypeDo tt = new TaskTypeDo();
    				tt.setId(ut.getTask().getTypeDo().getParentId());
    				List<TaskTypeDo> tts = taskTypeDao.select(tt);
    				if(tts!=null&&tts.size()>0){
    					ut.getTask().getTypeDo().setParentType(tts.get(0));
    				}
    			}else{
    				TaskTypeDo tt = new TaskTypeDo();
    				tt.setId(-1);
    				ut.getTask().setTypeDo(tt);
    			}
    		}
    		
    	}
		return new ResponseResult<List<UserTaskDo>>(StatusCode.SYSTEM_SUCCESS,tasks);
	}
    
    
    @PostMapping("/addTask")
    @ApiOperation(value="发布任务", notes="发布任务" ,httpMethod="POST")
    @ResponseBody
    @IgnoreSecurity
	@OpenApi
	@ApiImplicitParams({
   		@ApiImplicitParam(name="type", value="任务类型  1拼多多砍价 2拼多多现金 3其他", dataType = "number", required=false, paramType="form"),
   		@ApiImplicitParam(name="taskName", value="任务名称", dataType = "String", required=false, paramType="form"),
   		@ApiImplicitParam(name="stepOne", value="步骤一", dataType = "number", required=false, paramType="form"),
   		@ApiImplicitParam(name="stepTwo", value="步骤二", dataType = "number", required=false, paramType="form"),
   		@ApiImplicitParam(name="taskCount", value="任务单数", dataType = "number", required=false, paramType="form"),
   		@ApiImplicitParam(name="taskUrl", value="任务口令或链接", dataType = "number", required=false, paramType="form"),
   		@ApiImplicitParam(name="taskVerify", value="验证图", dataType = "number", required=false, paramType="form"),
   		@ApiImplicitParam(name="taskGold", value="金币数", dataType = "number", required=false, paramType="form"),
   		@ApiImplicitParam(name="validity", value="任务有效期 单位：分", dataType = "number", required=false, paramType="form"),
   		@ApiImplicitParam(name="slogan", value="口令 1 网址助力 2 二维码助力 3 自定义口令", dataType = "number", required=false, paramType="form")
   	})
    @SecurityData
	public  ResponseResult<Object> addTask(@RequestHeader(Constants.CLIENT_USER) Integer userId,@RequestBody @Validated AddTaskVo vo) {
    	try {
    		int f = 0;
    		TaskDo para = new TaskDo();
    		para.setUserId(userId);
    		List<TaskDo> ts = taskService.select(para);
    		if(ts!=null&&ts.size()>0){
    			f=1;
    		}
    		UserAccountDo account = userService.findUserAccountByUserId(userId);
    		Integer gcount = vo.getTaskCount()*vo.getTaskGold();
    		if(account==null||account.getGlod()==null||account.getGlod()<gcount){
    			return new ResponseResult<Object>(StatusCode.USER_ACCOUNT_NOT_ENOUGH, null);
    		}
    		TaskDo task = new TaskDo();
        	
        	if(vo.getType()!=null){
    			task.setType(vo.getType());
    		}

        	if(vo.getTaskCount()!=null){
    			task.setTaskCount(vo.getTaskCount());
    			task.setSurplusCount(vo.getTaskCount());
    		}
        	if(vo.getTaskName()!=null&&!"".equals(vo.getTaskName())){
    			task.setTaskName(vo.getTaskName());
    		}

        	if(vo.getTaskGold()!=null){
    			task.setTaskGold(vo.getTaskGold());
    		}
        	
        	if(vo.getStepOne()!=null&&!"".equals(vo.getStepOne())){
    			task.setStepOne(vo.getStepOne());
    		}
        	
        	if(vo.getStepTwo()!=null&&!"".equals(vo.getStepTwo())){
    			task.setStepTwo(vo.getStepTwo());
    		}

        	if(vo.getTaskUrl()!=null){
    			task.setTaskUrl(vo.getTaskUrl());
    		}
        	if(vo.getTaskVerify()!=null){
    			task.setTaskVerify(vo.getTaskVerify());
    		}
        	if(vo.getValidity()!=null){
    			task.setValidity(vo.getValidity());
    		}
        	if(vo.getSlogan()!=null){
    			task.setSlogan(vo.getSlogan());
    			if(vo.getSlogan()==3){
    				task.setType(-1);
    			}
    		}
        	task.setTaskStatus(0);
        	task.setCreateTime(new Date());
        	task.setUserId(userId);
        	int res = taskService.save(task);
        	if(res>0){
        		
        		if(f==1){
        			account.setGlod(account.getGlod()-gcount+110);
        		}else{
        			account.setGlod(account.getGlod()-gcount);
        		}
        		
        		userService.updateUserAccount(account);
        		
        		UserAccountRecordDo uar = new UserAccountRecordDo();
        		uar.setGlodType(2);
        		uar.setUserId(userId);
        		uar.setType(2);
        		uar.setTitle("发布任务");
        		uar.setCreateTime(new Date());
        		uar.setAmount(gcount);
        		userService.saveAccountRecord(uar);
        		
        		UserAccountRecordDo uar1 = new UserAccountRecordDo();
        		uar1.setGlodType(1);
        		uar1.setUserId(userId);
        		uar1.setType(16);
        		uar1.setTitle("首次发布任务");
        		uar1.setCreateTime(new Date());
        		uar1.setAmount(110);
        		userService.saveAccountRecord(uar1);
        		return new ResponseResult<Object>(StatusCode.SYSTEM_SUCCESS, task);
        	}else {
        		return new ResponseResult<Object>(StatusCode.SYSTEM_ERROR, null);
        	}
    		
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return new ResponseResult<Object>(StatusCode.SYSTEM_ERROR, null);
		}
    	
	}
    
    
    @GetMapping("/drawTask")
    @ApiOperation(value="领取任务", notes="领取任务" ,httpMethod="GET")
    @ResponseBody
    @IgnoreSecurity
	@OpenApi
	@ApiImplicitParams({
   		@ApiImplicitParam(name="taskId", value="任务Id", dataType = "number", required=false, paramType="form")
   	})
    @SecurityData
	public  ResponseResult<Object> drawTask(@RequestHeader(Constants.CLIENT_USER) Integer userId,Integer taskId) {
    	try {
    		
    		
    		/*SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
    		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
    		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    		Date start = sdf2.parse(sdf.format(new Date()));
    		Date end = sdf2.parse(sdf1.format(new Date()));
    		UserTaskDo ut = new UserTaskDo();
    		ut.setUserId(userId);
    		ut.setStartTime(start);
    		ut.setEndTime(end);
    		List<UserTaskDo> uts = userService.selectUserTask(ut);
    		if(uts!=null&&uts.size()>=10){
    			
    		}*/
    		
    		TaskDo t = taskService.findOne(taskId);
    		if(t.getUser().getId()==userId){
    			return new ResponseResult<Object>(StatusCode.CANNOT_GET_TASK, null);
    		}
    		if(t!=null&&t.getSurplusCount()>0) {
    			UserTaskDo task = new UserTaskDo();
            	task.setCreateTime(new Date());
            	task.setStatus(0);
            	task.setUserId(userId);
            	task.setTaskId(taskId);
            	int res = userService.saveUserTask(task);
            	if(res>0){
            		
            		if(t!=null&&t.getSurplusCount()>0){
            			t.setSurplusCount(t.getSurplusCount()-1);
            			taskService.update(t);
            		}
            	}
            	return new ResponseResult<Object>(StatusCode.SYSTEM_SUCCESS, res);
    		}else {
    			return new ResponseResult<Object>(StatusCode.TASK_COUNT_NOT_ENOUGH, null);
    		}
    		
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return new ResponseResult<Object>(StatusCode.SYSTEM_ERROR, null);
		}
    	
	}
    
    @PostMapping("/accountRecord")
    @ApiOperation(value="账户记录", notes="账户记录" ,httpMethod="POST")
    @ResponseBody
    @IgnoreSecurity
	@OpenApi
    @SecurityData
	public  ResponseResult<List<UserAccountRecordDo>> accountRecord(@RequestHeader(Constants.CLIENT_USER) Integer userId,@RequestBody @Validated UserAccountRecordPageVo vo) {
    	try {
    		List<UserAccountRecordDo> as = new ArrayList<UserAccountRecordDo>();
    		UserDo user = userService.findOne(userId);
    		if(user!=null){
    			UserAccountRecordDo ad = new UserAccountRecordDo();
    			if(vo.getPageNo()!=null){
        			Integer startNo = (vo.getPageNo()-1)*vo.getPageSize();
        			ad.setStartNo(startNo);
        			ad.setPageSize(vo.getPageSize());
        		}
    			ad.setUserId(userId);
    			as = userAccountRecordDao.select(ad);
    		}
    		
    		return new ResponseResult<List<UserAccountRecordDo>>(StatusCode.SYSTEM_SUCCESS, as);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return new ResponseResult<List<UserAccountRecordDo>>(StatusCode.SYSTEM_ERROR, null);
		}
    	
	}
    
    @PostMapping("/messages")
    @ApiOperation(value="消息记录", notes="消息记录" ,httpMethod="POST")
    @ResponseBody
    @IgnoreSecurity
	@OpenApi
    @SecurityData
	public  ResponseResult<List<MessageDo>> messages(@RequestHeader(Constants.CLIENT_USER) Integer userId,@RequestBody @Validated MessageVo vo) {
    	try {
    		MessageDo m = new MessageDo();
    		if(vo.getPageNo()!=null){
    			Integer startNo = (vo.getPageNo()-1)*vo.getPageSize();
    			m.setStartNo(startNo);
    			m.setPageSize(vo.getPageSize());
    		}
    		
    		if(vo.getType()!=null&&vo.getType()!=0){
    			m.setType(vo.getType());
    		}
    		m.setUserId(userId);
    		List<MessageDo> ms = messageDao.select(m);
    		if(ms!=null&&ms.size()>0){
    			for(MessageDo m1:ms){
    				if(m1.getType()==2){
    					UserTaskDo ut = userService.findOneUserTask(m1.getResourceId());
        				if(ut!=null){
        					TaskDo task = taskService.findOne(ut.getTaskId());
        					if(task!=null){
        						ut.setTask(task);
        						m1.setUserTask(ut);
        					}
        				}
    				}
    				
    			}
    		}
    		return new ResponseResult<List<MessageDo>>(StatusCode.SYSTEM_SUCCESS, ms);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return new ResponseResult<List<MessageDo>>(StatusCode.SYSTEM_ERROR, null);
		}
    	
	}
    
    @GetMapping("/readMessage")
    @ApiOperation(value="标记为已读", notes="标记为已读" ,httpMethod="GET")
    @ResponseBody
    @IgnoreSecurity
	@OpenApi
    @SecurityData
	public  ResponseResult<Object> readMessage(@RequestHeader(Constants.CLIENT_USER) Integer userId,Integer messageId) {
    	try {
    		
    		MessageDo m = new MessageDo();
    		
    		m.setId(messageId);
    		m.setIsRead(1);
    		messageDao.update(m);
    		
    		return new ResponseResult<Object>(StatusCode.SYSTEM_SUCCESS, null);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return new ResponseResult<Object>(StatusCode.SYSTEM_ERROR, null);
		}
    	
	}
    
    @GetMapping("/info")
    @ApiOperation(value="用户信息", notes="用户信息" ,httpMethod="GET")
    @ResponseBody
    @IgnoreSecurity
	@OpenApi
	@SecurityData
	@ApiImplicitParams({
   		@ApiImplicitParam(name="token", value="用户TOKEN", dataType = "String", required=false, paramType="form")
   	})
	public  ResponseResult<UserDo> info(String token) {
    	try {
        	String key = tokenManager.getKey(Constants.TOKEN_SHUAWUJING_FRONT,token);
        	if(key!=null&&!"".equals(key)){
        		
        		
        		UserDo res = userService.findByMobile(key);
        		
        		
        		Calendar ca = Calendar.getInstance();
        		ca.setTime(new Date());
        		ca.add(Calendar.DATE, -1);
        		
        		SigninDo sign = new SigninDo();
        		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        		sign.setUserId(res.getId());
        		sign.setTime(format.format(new Date()));
        		List<SigninDo> list = signinDao.select(sign);
    			if(list!=null&&list.size()>0){
    				res.setIsSign(1);
    				res.setCount(list.get(0).getCount());
    			}else{
    				sign.setTime(format.format(ca.getTime()));
    				list = signinDao.select(sign);
    				if(list!=null&&list.size()>0){
    					res.setIsSign(0);
    					res.setCount(list.get(0).getCount());
    				}else{
    					res.setIsSign(0);
    					res.setCount(0);
    				}
    			}
    			
    			
    			TaskDo task = new TaskDo();
    			task.setUserId(res.getId());
    			List<TaskDo> ts = taskDao.select(task);
    			if(ts!=null&&ts.size()>0){
    				res.setIsDeploy(1);
    			}else{
    				res.setIsDeploy(0);
    			}
    			
    			ShareDo share = new ShareDo();
        		share.setUserId(res.getId());
        		share.setTime(format.format(new Date()));
        		List<ShareDo> list1 = shareDao.select(share);
        		if(list1!=null&&list1.size()>0){
        			res.setIsShare(1);
        		}else{
        			res.setIsShare(0);
        		}
        		
        		InviteDo in = new InviteDo();
    			in.setUserId(res.getId());
    			List<InviteDo> is = inviteDao.select(in);
    			if(is!=null&&is.size()>0){
    				res.setIsBeInvite(1);
    			}else{
    				res.setIsBeInvite(0);
    			}
    			
        		
        		InviteDo in1 = new InviteDo();
    			in1.setInviteId(res.getId());
    			List<InviteDo> is1 = inviteDao.select(in1);
    			if(is1!=null&&is1.size()>0){
    				res.setIsInvite(1);
    			}else{
    				res.setIsInvite(0);
    			}
        		
        		UserAccountRecordDo uar = new UserAccountRecordDo();
        		uar.setUserId(res.getId());
        		uar.setTime(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        		int today = 0;
        		List<UserAccountRecordDo> uars = userAccountRecordDao.select(uar);
        		if(uars!=null&&uars.size()>0){
        			for(UserAccountRecordDo ua:uars){
        				if(ua.getGlodType()==1){
        					today+=ua.getAmount();
        				}else{
        					today-=ua.getAmount();
        				}
        			}
        		}
        		UserAccountDo ua = userService.findUserAccountByUserId(res.getId());
        		ua.setTodayGlod(today);
    			res.setUa(ua);
        		res.setAccessToken(token);
        		return new ResponseResult<UserDo>(StatusCode.SYSTEM_SUCCESS, res);
        	}else{
        		return new ResponseResult<UserDo>(StatusCode.TOKEN_ERROR, null);
        	}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return new ResponseResult<UserDo>(StatusCode.SYSTEM_ERROR, null);
		}
    	
	}
    
    @PostMapping("/updateUserTask")
    @ApiOperation(value="提交验证/审核用户提交的任务", notes="提交验证/审核用户提交的任务" ,httpMethod="POST")
    @ResponseBody
    @IgnoreSecurity
	@OpenApi
	@ApiImplicitParams({
   		@ApiImplicitParam(name="id", value="用户领取的任务主键", dataType = "number", required=false, paramType="form"),
   		@ApiImplicitParam(name="status", value="验证状态  2审核不通过 3 审核通过", dataType = "number", required=false, paramType="form"),
   		@ApiImplicitParam(name="verifyDetail", value="提交验证图", dataType = "String", required=false, paramType="form"),
   		@ApiImplicitParam(name="targetId", value="领取人用户ID", dataType = "number", required=false, paramType="form"),
   		@ApiImplicitParam(name="nopassReason", value="拒绝原因", dataType = "String", required=false, paramType="form"),
   		@ApiImplicitParam(name="nopassImg", value="拒绝图片", dataType = "String", required=false, paramType="form")
   	})
    @SecurityData
	public  ResponseResult<Object> updateUserTask(@RequestHeader(Constants.CLIENT_USER) Integer userId,@RequestBody @Validated UpdateUserTaskVo vo) {
    	try {
    		UserTaskDo ut1 = new UserTaskDo();
    		ut1.setUserId(vo.getTargetId());
    		ut1.setTaskId(vo.getId());
    		List<UserTaskDo> tasks = userService.selectUserTask(ut1);
    		UserTaskDo task = tasks.get(0);
    		if(vo.getStatus()!=null){
    			task.setStatus(vo.getStatus());
    		}else{
    			task.setStatus(1);
    		}
    		if(vo.getNopassReason()!=null&&!"".equals(vo.getNopassReason())){
    			task.setNopassReason(vo.getNopassReason());
    		}
    		if(vo.getNopassImg()!=null&&!"".equals(vo.getNopassImg())){
    			task.setNopassImg(vo.getNopassImg());
    		}
    		if(vo.getVerifyDetail()!=null&&!"".equals(vo.getVerifyDetail())){
    			task.setVerifyDetail(vo.getVerifyDetail());
    		}
    		
    		
        	
        	int res = userService.updateUserTask(task);
        	if(res>0){
        		
        		if(vo.getVerifyDetail()!=null&&!"".equals(vo.getVerifyDetail())){
        			System.out.println(task.getTask()+"22222---------------------");
        			if(task.getTask()!=null&&task.getTask().getSurplusCount()>=0){
        				
        				System.out.println(task.getTask()+"---------------------");
        				UserDo user = userService.findOne(task.getTask().getUser().getId());
        				System.out.println("token---------------------"+user.getDeviceToken());
        				if(user.getDeviceToken()!=null&&user.getDeviceToken().length()==64) {
        					Demo demo = new Demo();
        					
        					
        					List<UmengExtra> list = new ArrayList<UmengExtra>();
        					UmengExtra ue = new UmengExtra();
        					ue.setKey("type");
        					ue.setValue(1);
        					list.add(ue);
        					UmengExtra ue1 = new UmengExtra();
        					ue1.setKey("resourceId");
        					ue1.setValue(task.getTask().getId());
        					list.add(ue1);
        					String text = "";
        					if(task.getTask().getTypeDo()==null){
        						text = "您好，有人提交了您发布的"+task.getTask().getTaskName()+"任务，快去审核吧！";
                			}else{
                				text = "您好，有人提交了您发布的"+task.getTask().getTypeDo().getName()+"任务，快去审核吧！";
                			}
        					JSONObject alert = new JSONObject();
        					alert.put("title", "提交任务通知");
        					//alert.put("subtitle", "提交任务通知");
        					alert.put("body", text);
        					demo.sendIOSUnicast(user.getDeviceToken(), alert,list);
        				}
        				
        				if(user.getDeviceToken()!=null&&user.getDeviceToken().length()==44) {
        					System.out.println("token11111---------------------"+user.getDeviceToken());
        					Demo demo = new Demo();
        					String alert="提交任务通知";
        					List<UmengExtra> list = new ArrayList<UmengExtra>();
        					UmengExtra ue = new UmengExtra();
        					ue.setKey("type");
        					ue.setValue(1);
        					list.add(ue);
        					UmengExtra ue1 = new UmengExtra();
        					ue1.setKey("resourceId");
        					ue1.setValue(task.getTask().getId());
        					list.add(ue1);
        					String text = "";
        					if(task.getTask().getTypeDo()==null){
        						text = "您好，有人提交了您发布的"+task.getTask().getTaskName()+"任务，快去审核吧！";
                			}else{
                				text = "您好，有人提交了您发布的"+task.getTask().getTypeDo().getName()+"任务，快去审核吧！";
                			}
        					
        					demo.sendAndroidUnicast(user.getDeviceToken(), "任务提交","任务提交",text, list);
        				}
        			}
        		}
        		if(vo.getStatus()!=null&&vo.getStatus()==1){
        			if(task.getTask()!=null&&task.getTask().getSurplusCount()>0){
        				task.getTask().setSurplusCount(task.getTask().getSurplusCount()-1);
        				taskService.update(task.getTask());
        			}
        		}
        		if(vo.getStatus()!=null&&vo.getStatus()==2){
        			
        			
        			if(task.getTask()!=null&&task.getTask().getSurplusCount()>0){
        				task.getTask().setSurplusCount(task.getTask().getSurplusCount()+1);
        				taskService.update(task.getTask());
        				
        				MessageDo message = new MessageDo();
            			message.setCreateTime(new Date());
            			message.setIsRead(0);
            			message.setUserId(task.getUser().getId());
            			if(task.getTask().getTypeDo()==null){
            				message.setTitle("您好，您提交的的"+task.getTask().getTaskName()+"任务，被对方审核不通过，如有疑问，请联系客服介入。");
            			}else{
            				message.setTitle("您好，您提交的的"+task.getTask().getTypeDo().getName()+"任务，被对方审核不通过，如有疑问，请联系客服介入。");
            			}
            			
            			message.setType(2);
            			message.setResourceId(task.getTask().getId());
            			messageDao.save(message);
            			
            			UserDo user = userService.findOne(task.getUser().getId());
        				if(user.getDeviceToken()!=null&&user.getDeviceToken().length()==64) {
        					Demo demo = new Demo();
        					
        					List<UmengExtra> list = new ArrayList<UmengExtra>();
        					UmengExtra ue = new UmengExtra();
        					ue.setKey("type");
        					ue.setValue(2);
        					list.add(ue);
        					UmengExtra ue1 = new UmengExtra();
        					ue1.setKey("resourceId");
        					ue1.setValue(task.getTask().getId());
        					list.add(ue1);
        					String text = "";
        					if(task.getTask().getTypeDo()==null){
        						text = "您好，您提交的的"+task.getTask().getTaskName()+"任务，被对方审核不通过，如有疑问，请联系客服介入。";
                			}else{
                				text = "您好，您提交的的"+task.getTask().getTypeDo().getName()+"任务，被对方审核不通过，如有疑问，请联系客服介入。";
                			}
        					JSONObject alert = new JSONObject();
        					alert.put("title", "审核拒绝通知");
        					//alert.put("subtitle", "审核拒绝通知");
        					alert.put("body", text);
        					demo.sendIOSUnicast(user.getDeviceToken(), alert,list);
        					
        				}
        				
        				if(user.getDeviceToken()!=null&&user.getDeviceToken().length()==44) {
        					Demo demo = new Demo();
        					List<UmengExtra> list = new ArrayList<UmengExtra>();
        					UmengExtra ue = new UmengExtra();
        					ue.setKey("type");
        					ue.setValue(2);
        					list.add(ue);
        					UmengExtra ue1 = new UmengExtra();
        					ue1.setKey("resourceId");
        					ue1.setValue(task.getTask().getId());
        					list.add(ue1);
        					String text = "";
        					if(task.getTask().getTypeDo()==null){
        						text = "您好，您提交的的"+task.getTask().getTaskName()+"任务，被对方审核不通过，如有疑问，请联系客服介入。";
                			}else{
                				text = "您好，您提交的的"+task.getTask().getTypeDo().getName()+"任务，被对方审核不通过，如有疑问，请联系客服介入。";
                			}
        					
        					demo.sendAndroidUnicast(user.getDeviceToken(), "审核拒绝","审核拒绝",text, list);
        					
        				}
        			}
        		}
        		
        		if(vo.getStatus()!=null&&vo.getStatus()==3){
        		
        			UserAccountDo account = userService.findUserAccountByUserId(task.getUser().getId());
        			account.setGlod(account.getGlod()+task.getTask().getTaskGold());
        			userService.updateUserAccount(account);
        			
        			UserAccountRecordDo uar = new UserAccountRecordDo();
        			uar.setAmount(task.getTask().getTaskGold());
        			uar.setCreateTime(new Date());
        			uar.setUserId(task.getUser().getId());
        			uar.setGlodType(1);
        			uar.setType(3);
        			uar.setTitle("完成任务");
        			userService.saveAccountRecord(uar);
        			
        			MessageDo message = new MessageDo();
        			message.setCreateTime(new Date());
        			message.setIsRead(0);
        			message.setUserId(task.getUser().getId());
        			message.setResourceId(task.getTask().getId());
        			if(task.getTask().getTypeDo()==null){
        				message.setTitle(task.getTask().getTaskGold()+"金币已到账，您提交的"+task.getTask().getTaskName()+"任务已被对方审核通过。");
        			}else{
        				message.setTitle(task.getTask().getTaskGold()+"金币已到账，您提交的"+task.getTask().getTypeDo().getName()+"任务已被对方审核通过。");
        			}
        			
        			message.setType(2);
        			messageDao.save(message);
        			
        		}
        	}
    		return new ResponseResult<Object>(StatusCode.SYSTEM_SUCCESS, res);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return new ResponseResult<Object>(StatusCode.SYSTEM_ERROR, null);
		}
    	
	}
    
    
    @GetMapping("/myTasks")
    @ApiOperation(value="我发布的任务", notes="我发布的任务" ,httpMethod="GET")
    @ResponseBody
    @IgnoreSecurity
	@OpenApi
	@SecurityData
	public  ResponseResult<List<TaskDo>> myTasks(@RequestHeader(Constants.CLIENT_USER) Integer userId,Integer pageNo,Integer pageSize) {
    	try {
    		TaskDo task = new TaskDo(); 
        	
        	task.setUserId(userId);
        	Integer startNo = (pageNo-1)*pageSize;
			task.setStartNo(startNo);
			task.setPageSize(pageSize);
			task.setSortCloum(" t.create_time desc");
        	List<TaskDo> list = taskService.select(task);
        	if(!CollectionUtils.isEmpty(list)){
        		for(TaskDo t:list){
        			
        			if(t.getTypeDo()!=null){
        				TaskTypeDo tt = new TaskTypeDo();
        				tt.setId(t.getTypeDo().getParentId());
        				List<TaskTypeDo> tts = taskTypeDao.select(tt);
        				if(tts!=null&&tts.size()>0){
        					t.getTypeDo().setParentType(tts.get(0));
        				}
        			}else{
        				TaskTypeDo tt = new TaskTypeDo();
        				tt.setId(-1);
        				t.setTypeDo(tt);
        			}
        			UserTaskDo ut = new UserTaskDo();
        			ut.setTaskId(t.getId());
        			ut.setStatus(0);
        			List<UserTaskDo> uts = userService.orderTaking(ut);
        			if(!CollectionUtils.isEmpty(list)){
        				t.setNotSubmit(uts.size());
        			}
        			ut.setStatus(1);
        			uts = userService.orderTaking(ut);
        			if(!CollectionUtils.isEmpty(list)){
        				t.setWaitVerify(uts.size());
        			}
        			ut.setStatus(3);
        			uts = userService.orderTaking(ut);
        			if(!CollectionUtils.isEmpty(list)){
        				t.setAuditAgree(uts.size());
        			}
        			ut.setStatus(2);
        			uts = userService.orderTaking(ut);
        			if(!CollectionUtils.isEmpty(list)){
        				t.setAuditRejection(uts.size());
        			}
        			
        			ut.setStatus(4);
        			uts = userService.orderTaking(ut);
        			if(!CollectionUtils.isEmpty(list)){
        				t.setAppeal(uts.size());
        			}
        		}
        	}
    		return new ResponseResult<List<TaskDo>>(StatusCode.SYSTEM_SUCCESS, list);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return new ResponseResult<List<TaskDo>>(StatusCode.SYSTEM_ERROR, null);
		}
    	
	}
    
    
    @GetMapping("/notSubmitCount")
    @ApiOperation(value="等我提交", notes="等我提交" ,httpMethod="GET")
    @ResponseBody
    @IgnoreSecurity
	@OpenApi
	@SecurityData
	public  ResponseResult<Object> notSubmitCount(@RequestHeader(Constants.CLIENT_USER) Integer userId) {
    	try {
    		
    		UserTaskDo ut = new UserTaskDo();
    		
    		ut.setUserId(userId);
    		ut.setStatus(0);
    		
    		List<UserTaskDo> list = userService.findAllUserTask(ut);
    		if(list!=null&&list.size()>0){
    			return new ResponseResult<Object>(StatusCode.SYSTEM_SUCCESS, list.size());
    		}else{
    			return new ResponseResult<Object>(StatusCode.SYSTEM_SUCCESS, 0);
    		}
    		
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return new ResponseResult<Object>(StatusCode.SYSTEM_ERROR, null);
		}
    	
	}
    
    
    @PostMapping("/appeal")
    @ApiOperation(value="申诉", notes="申诉" ,httpMethod="POST")
    @ApiImplicitParams({
   		@ApiImplicitParam(name="userTaskId", value="申诉的接单ID", dataType = "number", required=false, paramType="form"),
   		@ApiImplicitParam(name="appealDetail", value="申诉详情", dataType = "String", required=false, paramType="form"), 	
   		@ApiImplicitParam(name="verifyImg", value="申诉图片", dataType = "String", required=false, paramType="form")
   	})
    @ResponseBody
    @IgnoreSecurity
	@OpenApi
	@SecurityData
	public  ResponseResult<Object> myTasks(@RequestHeader(Constants.CLIENT_USER) Integer userId,@RequestBody @Validated AddAppealVo vo) {
    	try {
    		
    		UserTaskDo ut = userService.findOneUserTask(vo.getUserTaskId());
    		
    		if(ut!=null){
    			AppealDo app = new AppealDo();
    			app.setStatus(0);
    			
    			//TaskDo task = taskService.findOne(ut.getTaskId());
    			app.setTaskId(ut.getTaskId());
    			app.setUserId(userId);
    			app.setVerifyImg(vo.getVerifyImg());
    			app.setUserTaskId(vo.getUserTaskId());
    			
    			if(vo.getAppealDetail()!=null&&!"".equals(vo.getAppealDetail())){
    				app.setAppealDetail(vo.getAppealDetail());
    			}
    			
    			if(vo.getVerifyReason()!=null&&!"".equals(vo.getVerifyReason())){
    				app.setVerifyReason(vo.getVerifyReason());
    			}
    			app.setCreateTime(new Date());
    			
    			int res = appealDao.save(app);
    			return new ResponseResult<Object>(StatusCode.SYSTEM_SUCCESS, res);
    		}else{
    			return new ResponseResult<Object>(StatusCode.SYSTEM_ERROR, null);
    		}
    		
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return new ResponseResult<Object>(StatusCode.SYSTEM_ERROR, null);
		}
    	
	}
    
    
    @PostMapping("/update")
    @ApiOperation(value="修改个人资料", notes="修改个人资料" ,httpMethod="POST")
    @ApiImplicitParams({
   		@ApiImplicitParam(name="userTaskId", value="申诉的接单ID", dataType = "number", required=false, paramType="form"),
   		@ApiImplicitParam(name="appealDetail", value="申诉详情", dataType = "String", required=false, paramType="form"), 	
   		@ApiImplicitParam(name="verifyImg", value="申诉图片", dataType = "String", required=false, paramType="form")
   	})
    @ResponseBody
    @IgnoreSecurity
	@OpenApi
	@SecurityData
	public  ResponseResult<Object> update(@RequestHeader(Constants.CLIENT_USER) Integer userId,@RequestBody @Validated UpdateUserVo vo) {
    	try {
    		
    		
    		UserDo user = userService.findOne(userId);
    		if(vo.getBirth()!=null&&!"".equals(vo.getBirth())){
    			user.setBirth(vo.getBirth());
    		}
    		if(vo.getHeadImg()!=null&&!"".equals(vo.getHeadImg())){
    			user.setHeadImage(vo.getHeadImg());
    		}
    		if(vo.getSex()!=null){
    			user.setSex(vo.getSex());
    		}
    		if(vo.getUserName()!=null&&!"".equals(vo.getUserName())){
    			user.setUserName(vo.getUserName());
    		}
    		
    		int res = userService.update(user);
    		if(res>0){
    			return new ResponseResult<Object>(StatusCode.SYSTEM_SUCCESS, res);
    		}else{
    			return new ResponseResult<Object>(StatusCode.SYSTEM_ERROR, null);
    		}
    		
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return new ResponseResult<Object>(StatusCode.SYSTEM_ERROR, null);
		}
    	
	}
    
    
    @GetMapping("/sign")
    @ApiOperation(value="签到", notes="签到" ,httpMethod="GET")
    @IgnoreSecurity
	@OpenApi
	@SecurityData
	@ResponseBody
	public  ResponseResult<SigninDo> sign(@RequestHeader(Constants.CLIENT_USER) Integer userId) {
    	try {
    		int res;
    		Calendar ca = Calendar.getInstance();
    		ca.setTime(new Date());
    		ca.add(Calendar.DATE, -1);
    		
    		SigninDo sign = new SigninDo();
    		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    		sign.setUserId(userId);
    		sign.setTime(format.format(ca.getTime()));
    		List<SigninDo> list = signinDao.select(sign);

    		sign.setUserId(userId);
    		sign.setTime(format.format(new Date()));
    		List<SigninDo> list1 = signinDao.select(sign);
    		if(list1!=null&&list1.size()>0){
    			return new ResponseResult<SigninDo>(StatusCode.ALREADY_SIGN, null);
    		}
    		
    		if(list!=null&&list.size()>0){
    			int count = list.get(0).getCount();
    			int glod = 16;
    			if(count==1){
        			glod = 26;
        		}else if(count==2){
        			glod = 36;
        		}else if(count==3){
        			glod = 56;
        		}else if(count==4){
        			glod = 66;
        		}else if(count==5){
        			glod = 86;
        		}else{
        			glod = 100;
        		}
    			sign.setCreateTime(new Date());
    			sign.setGlod(glod);
    			sign.setCount(list.get(0).getCount()+1);
    			res = signinDao.save(sign);
    			
    			UserAccountDo ua = userService.findUserAccountByUserId(userId);
    			ua.setGlod(ua.getGlod()+glod);
    			userService.updateUserAccount(ua);
    			
    			UserAccountRecordDo uar = new UserAccountRecordDo();
    			uar.setAmount(glod);
    			uar.setCreateTime(new Date());
    			uar.setGlodType(1);
    			uar.setTitle("用户签到");
    			uar.setUserId(userId);
    			uar.setType(15);
    			int res1  =userAccountRecordDao.save(uar);
    			
    			if(res1>0){
        			return new ResponseResult<SigninDo>(StatusCode.SYSTEM_SUCCESS, sign);
        		}else{
        			return new ResponseResult<SigninDo>(StatusCode.SYSTEM_ERROR, null);
        		}
        		
    		}else{
    			sign.setCreateTime(new Date());
    			sign.setGlod(16);
    			sign.setCount(1);
    			res = signinDao.save(sign);
    			
    			UserAccountDo ua = userService.findUserAccountByUserId(userId);
    			ua.setGlod(ua.getGlod()+16);
    			userService.updateUserAccount(ua);
    			
    			UserAccountRecordDo uar = new UserAccountRecordDo();
    			uar.setAmount(16);
    			uar.setCreateTime(new Date());
    			uar.setGlodType(1);
    			uar.setTitle("用户签到");
    			uar.setUserId(userId);
    			uar.setType(15);
    			int res1 = userAccountRecordDao.save(uar);
    			if(res1>0){
        			return new ResponseResult<SigninDo>(StatusCode.SYSTEM_SUCCESS, sign);
        		}else{
        			return new ResponseResult<SigninDo>(StatusCode.SYSTEM_ERROR, null);
        		}
    		}
    		
    		
    		
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return new ResponseResult<SigninDo>(StatusCode.SYSTEM_ERROR, null);
		}
    	
	}
    
    @GetMapping("/share")
    @ApiOperation(value="分享", notes="分享" ,httpMethod="GET")
    @IgnoreSecurity
	@OpenApi
	@SecurityData
	@ResponseBody
	public  ResponseResult<Object> share(@RequestHeader(Constants.CLIENT_USER) Integer userId) {
    	try {
    		
    		ShareDo share = new ShareDo();
    		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    		share.setUserId(userId);
    		share.setTime(format.format(new Date()));
    		List<ShareDo> list = shareDao.select(share);
    		if(list!=null&&list.size()>0){
    			return new ResponseResult<Object>(StatusCode.ALREADY_SHARE, null);
    		}else{
    			UserAccountDo ua = userService.findUserAccountByUserId(userId);
    			ua.setGlod(ua.getGlod()+60);
    			userService.updateUserAccount(ua);
    			
    			UserAccountRecordDo uar = new UserAccountRecordDo();
    			uar.setAmount(60);
    			uar.setCreateTime(new Date());
    			uar.setGlodType(1);
    			uar.setTitle("分享群聊");
    			uar.setType(14);
    			uar.setUserId(userId);
    			
    			
    			ShareDo param = new ShareDo();
    			param.setCreateTime(new Date());
    			param.setUserId(userId);
    			param.setGlod(60);
    			
    			shareDao.save(param);
    			int res1 = userAccountRecordDao.save(uar);
    			if(res1>0){
        			return new ResponseResult<Object>(StatusCode.SYSTEM_SUCCESS, 60);
        		}else{
        			return new ResponseResult<Object>(StatusCode.SYSTEM_ERROR, null);
        		}
    		}
    		
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return new ResponseResult<Object>(StatusCode.SYSTEM_ERROR, null);
		}
    	
	}
  
    @PostMapping("/withdraws")
    @ApiOperation(value="提现记录", notes="提现记录" ,httpMethod="POST")
    @ResponseBody
    @IgnoreSecurity
	@OpenApi
	@SecurityData
	public  ResponseResult<List<WithdrawDo>> withdraws(@RequestHeader(Constants.CLIENT_USER) Integer userId,@RequestBody @Validated UserWithdrawVo vo) {
    	try {
    		WithdrawDo w = new WithdrawDo();
        	if(vo.getPageNo()!=null){
    			Integer startNo = (vo.getPageNo()-1)*vo.getPageSize();
    			w.setStartNo(startNo);
    			w.setPageSize(vo.getPageSize());
    		}
        	w.setUserId(userId);
        	List<WithdrawDo> list = withdrawDao.select(w);
       
    		return new ResponseResult<List<WithdrawDo>>(StatusCode.SYSTEM_SUCCESS, list);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return new ResponseResult<List<WithdrawDo>>(StatusCode.SYSTEM_ERROR, null);
		}
    	
	}
    
    @PostMapping("/withdraw")
    @ApiOperation(value="提现", notes="提现" ,httpMethod="POST")
    @ResponseBody
    @IgnoreSecurity
	@OpenApi
	@SecurityData
	public  ResponseResult<Object> withdraws(@RequestHeader(Constants.CLIENT_USER) Integer userId,@RequestBody @Validated WithDrawAddVo vo) {
    	try {
    		
    		if(!isPhone(vo.getAccountNum())&&!checkEmail(vo.getAccountNum())){
    			return new ResponseResult<Object>(StatusCode.AOUNT_ERROR, null);
    		}
    		UserAccountDo ua = userService.findUserAccountByUserId(userId);
    		if(ua.getGlod()==null||ua.getGlod()<vo.getGlod()){
    			return new ResponseResult<Object>(StatusCode.USER_ACCOUNT_NOT_ENOUGH, null);
    		}
    		WithdrawDo w1 = new WithdrawDo();
        	
        	w1.setUserId(userId);
        	List<WithdrawDo> list = withdrawDao.select(w1);
        	if(list!=null&&list.size()>0){
        		if(vo.getGlod()==10000){
        			return new ResponseResult<Object>(StatusCode.WITHDRAW_ERROR, null);
        		}
        	}
    		WithdrawDo w = new WithdrawDo();
    		if(vo.getGlod()!=null){
    			w.setGload(vo.getGlod());
    			
    		}
    		w.setAccountName(vo.getAccountName());
    		w.setAccountNum(vo.getAccountNum());
    		w.setCreateTime(new Date());
    		w.setUserId(userId);
    		w.setAmount(vo.getGlod()/10000);
    		
    		
    		int res = withdrawDao.save(w);
    		
    		if(ua!=null){
    			ua.setGlod(ua.getGlod()-vo.getGlod());
    			ua.setCanWithdraw(ua.getGlod()/100);
    			userService.updateUserAccount(ua);
    		}
    		return new ResponseResult<Object>(StatusCode.SYSTEM_SUCCESS, res);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return new ResponseResult<Object>(StatusCode.SYSTEM_ERROR, null);
		}
    	
	}
    
    
    public static boolean isPhone(String phone) {
        boolean isPass = true;
        if (phone.length() == 0) {
           isPass = false;
        } else if (!phone.matches("^[1][3,4,5,7,8][0-9]{9}$")) {
           isPass = false;
        }
        return isPass;
     }
    
    /**
     * 验证邮箱地址是否正确
     * @param email
     * @return
     */
    public static boolean checkEmail(String email){
        boolean flag = false;
        try{
            String check = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
            Pattern regex = Pattern.compile(check);
            Matcher matcher = regex.matcher(email);
            flag = matcher.matches();
        }catch(Exception e){
            flag = false;
        }

        return flag;
    }
}

